<?php

/**
 * 律师管理控制器
 */

declare(strict_types=1);

namespace app\controller\lawyer;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use app\model\lawyer\Lawyer as LawyerModel;
use app\model\system\Region;
use app\model\system\File;

class Lawyer extends BaseController
{
    /**
     * 无需登录的方法
     * @var array
     */
    
    /**
     * 查看律师列表
     */
    public function list()
    {
        $param = Request::param();

        try {
            // 使用模型获取律师列表
            $result = LawyerModel::getList($param);
            $list = $result['list'];
            $count = $result['count'];

            // 格式化数据
            $list = array_map(function ($item) {
                // 使用模型方法格式化数据，如果是对象则转为数组，如果已经是数组则直接使用
                if (is_object($item)) {
                    return LawyerModel::formatData($item->toArray());
                } else {
                    return LawyerModel::formatData($item);
                }
            }, $list);

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 查看单个律师信息
     */
    public function view()
    {
        $param = Request::param();

        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        try {
            // 使用模型获取律师详情
            $lawyer = LawyerModel::getDetail($param['id']);

            if (empty($lawyer)) {
                return json(['code' => 404, 'msg' => '律师信息不存在']);
            }

            // 转换为数组
            // 若 $lawyer 已是数组则不转换，避免错误
            if (is_object($lawyer)) {
                $lawyer = $lawyer->toArray();
            }

            // 使用模型方法格式化数据
            $lawyer = LawyerModel::formatData($lawyer);

            // 获取附件信息
            /*
            if (!empty($lawyer['file_ids'])) {
                $fileIds = explode(',', $lawyer['file_ids']);
                $fileInfo = File::getFileInfoByIds($fileIds);
                $lawyer['file_array'] = array_values($fileInfo);
            }
            */

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $lawyer
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取启用的律师列表（用于下拉选择）
     */
    public function set()
    {
        try {
            // 使用模型获取启用的律师列表
            $list = LawyerModel::getEnableList();

            // 格式化数据
            $list = array_map(function ($item) {
                // 使用模型方法格式化数据，如果是对象则转为数组，如果已经是数组则直接使用
                if (is_object($item)) {
                    return LawyerModel::formatData($item->toArray());
                } else {
                    return LawyerModel::formatData($item);
                }
            }, $list);

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取律所律师列表（用于案件管理选择）
     */
    public function getLawFirmLawyers()
    {
        try {
            $lawfirmId = $this->request->param('lawfirm_id', 0, 'intval');
            $keywords = $this->request->param('keywords', '');
            
            $query = LawyerModel::where('status', 1);
            
            if ($lawfirmId) {
                $query->where('firmid', $lawfirmId);
            }
            
            if ($keywords) {
                $query->where('name', 'like', "%{$keywords}%");
            }
            
            $list = $query->field('id, name, firm_name, type, lawyer_license, mobile, email')
                ->order('id', 'desc')
                ->select()
                ->toArray();
                
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 切换律师登录权限
     */
    public function toggleLoginPermission()
    {
        // 获取POST参数
        $param = Request::param();
        $id = isset($param['id']) ? intval($param['id']) : 0;
        $canLogin = isset($param['can_login']) ? intval($param['can_login']) : 0;
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 使用withoutSoftDelete作用域查询律师，包括已软删除的记录
            $lawyer = LawyerModel::withoutSoftDelete()->find($id);
            if (!$lawyer) {
                return json(['code' => 404, 'msg' => '律师不存在']);
            }
            
            // 直接使用数据库更新，绕过模型的变更检测
            $result = Db::name('lawyer')->where('id', $id)->update([
                'can_login' => $canLogin,
                'update_time' => time()
            ]);
            
            if ($result !== false) {
                return json(['code' => 0, 'msg' => '更新成功']);
            } else {
                return json(['code' => 500, 'msg' => '更新失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 新增律师
     */
    public function add()
    {
        $param = Request::param();

        // 数据验证
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '律师姓名不能为空']);
        }

        if (empty($param['lawfirm_id'])) {
            return json(['code' => 400, 'msg' => '请选择所属律所']);
        }

        if (empty($param['mobile'])) {
            return json(['code' => 400, 'msg' => '手机号不能为空']);
        }

        // 处理资格取得日期（保持为时间戳）
        $qualificationDate = !empty($param['qualification_date']) ? (int)$param['qualification_date'] : 0;

        // 生成用户名（使用手机号作为用户名）
        $username = $param['mobile'];
        
        // 检查用户名是否已存在
        $existing = LawyerModel::where('username', $username)->find();
        if ($existing) {
            return json(['code' => 400, 'msg' => '该手机号已被注册']);
        }

        $data = [
            'username' => $username,
            'name' => $param['name'],
            'mobile' => $param['mobile'],
            'firmid' => $param['lawfirm_id'],
            'sex' => $param['sex'] ?? 1,
            'email' => $param['email'] ?? '',
            'idcard' => $param['idcard'] ?? '',
            'provinceid' => $param['provinceid'] ?? 0,
            'cityid' => $param['cityid'] ?? 0,
            'distid' => $param['distid'] ?? 0,
            'type' => $param['type'] ?? 0,
            'entry_time' => $qualificationDate,
            'status' => $param['status'] ?? 1,
            'create_time' => time(),
            'update_time' => time()
        ];

        try {
            // 使用模型新增律师
            $lawyer = new LawyerModel();
            $lawyer->save($data);
            $lawyerId = $lawyer->id;

            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $lawyerId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 编辑律师
     */
    public function edit()
    {
        $param = Request::param();

        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '律师姓名不能为空']);
        }

        if (empty($param['lawfirm_id'])) {
            return json(['code' => 400, 'msg' => '请选择所属律所']);
        }

        // 处理资格取得日期（保持为时间戳）
        $qualificationDate = !empty($param['qualification_date']) ? (int)$param['qualification_date'] : 0;

        $data = [
            'name' => $param['name'],
            'firmid' => $param['lawfirm_id'],
            'mobile' => $param['mobile'] ?? '',
            'sex' => $param['sex'] ?? 1,
            'email' => $param['email'] ?? '',
            'idcard' => $param['idcard'] ?? '',
            'provinceid' => $param['provinceid'] ?? 0,
            'cityid' => $param['cityid'] ?? 0,
            'distid' => $param['distid'] ?? 0,
            'type' => $param['type'] ?? 0,
            'entry_time' => $qualificationDate,
            'status' => $param['status'] ?? 1,
            'update_time' => time()
        ];

        // 如果提供了手机号，检查是否已被其他律师使用
        if (!empty($param['mobile'])) {
            $existing = LawyerModel::where('mobile', $param['mobile'])
                ->where('id', '<>', $param['id'])
                ->find();
            if ($existing) {
                return json(['code' => 400, 'msg' => '该手机号已被其他律师使用']);
            }
        }

        try {
            // 使用模型更新律师信息
            LawyerModel::update($data, ['id' => $param['id']]);

            return json(['code' => 0, 'msg' => '编辑成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '编辑失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 删除律师（软删除）
     */
    public function del()
    {
        $param = Request::param();

        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        try {
            // 使用模型进行软删除
            $lawyer = LawyerModel::find($param['id']);
            if ($lawyer) {
                $lawyer->delete();
            }

            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
}